<?php
namespace Home\Controller;
use Think\Controller;
class AjaxController extends CommonController {
	//检查用户名是否可用
    public function checkUsername(){
        if(!IS_AJAX) {$this->error('非法访问！');}
        $username=I('username');
        $where=array('username'=>$username);
        if(!M('user')->where($where)->getField('id')){
        	echo 1;
        }else{
        	echo -1;
        }
    }


    //检查邮箱是否可用
    public function checkEmail(){
    	if(!IS_AJAX) {$this->error('非法访问！');}
        $email=I('email');
        $where=array('email'=>$email);
        if(!M('userinfo')->where($where)->getField('id')){
        	echo 1;
        }else{
        	echo -1;
        }
    }

    //执行注册操作
    public function regsave(){
    	$obj=array(
    		'username'=>I('username'),
    		'password'=>md5(I('pwd')),
    		'regtime'=>time(),
    		'userinfo'=>array(
    			'nickname'=>I('username'),
    			'email'=>I('email'),
    			'checkcode'=>md5(uniqid()),
    			'points'=>C('REG'),
    			'logintime'=>time(),
    			'loginip'=>get_client_ip(),
    			),
    		);
    	if($id=D('user')->relation(true)->data($obj)->add()){
    		$link=SITEURL.'index.php/Home/Ajax/active/uid/'.$id.'/checkcode/'.$obj['userinfo']['checkcode'];
    		sendMail(I('email'),'童老师素材站账号激活','点击激活账号'.$link);
    		session('uid',$id);
	    	session('username',I('username'));
    		$data['error']='';
	    	$data['tip']='注册成功 增加20积分！';
	    	$data['avatar']='http://www.sucaihuo.com/Public/images/avatar.jpg';
	    	echo json_encode($data);
    	}else{
    		$data['error']='注册失败！';
    		echo json_encode($data);
    	}
	}

	//邮箱激活
	public function active(){
		$id=I('uid');
		$checkcode=I('checkcode');
		$userinfo=D('userinfo');
		$where=array(
			'checkemail'=>0,
			'uid'=>$id,
			);
		$userinfos=$userinfo->where($where)->find();
		if($userinfos['checkcode']==$checkcode){
			$arr=array(
				'id'=>$userinfos['id'],
				'checkemail'=>1,
				'checkcode'=>'',
				'points'=>$userinfos['points']+C('checkEmail'),
				);
			if($userinfo->save($arr)){
				$this->success('激活成功！',U('Index/index'));
			}else{
				$this->error('激活失败！',U('Index/index'));
			}

		}else{
			$this->error('邮箱已经激活！',U('Account/Login'));
		}
	}

	//异步发送邮件
	public function email_check(){
		$id=session('uid');
		$userinfo=D('userinfo');
		$userinfos=$userinfo->where(array('uid'=>$id))->find();
		$link=SITEURL.'index.php/Home/Ajax/active/uid/'.$id.'/checkcode/'.$userinfos['checkcode'];
    	if(sendMail($userinfos['email'],'童老师素材站账号激活','点击激活账号'.$link)){
    		echo 1;
    	}else{
    		echo 0;
    	}
		
	}

	//异步登录方法

	public function checkLogin(){
		$username=I('username');
		$password=md5(I('pwd'));
		$rememberme=I('rememberme');
		$where=array('username'=>$username);
		$user=D('user')->relation(true)->where($where)->find();
		if(!$user || $user['password'] != $password){
			$data['error']='登录失败！';
    		echo json_encode($data);
    		die;
		}
		if($user['lock']){
			$data['error']='用户被锁定，无法登录！';
    		echo json_encode($data);
    		die;
		}else{
			//是否记住密码   1|127.0.0.1|tongpan8
			if($rememberme==1){
				$value=$user['id'].'|'.get_client_ip().'|'.$user['username'];
				$value=encrypt($value,1);
				setcookie('sucai',$value,time()+3600*24*7*2,'/');
			}
			//如果当前时间戳小于今天零时零分时间戳，就增加分值
			$today=strtotime(date('Y-m-d'));
			if($today>$user['logintime']){
				$arr=array(
					'id'=>$user['id'],
					'userinfo'=>array(
						'points'=>$user['points']+C('LOGIN'),
					),
					);
				D('user')->relation(true)->where(array('id'=>$user['id']))->save($arr);
			}
			//登录成功后更新最后一次登录时间戳
			$arr=array(
				'id'=>$user['id'],
				'userinfo'=>array(
					'logintime'=>time(),
					'loginip'=>get_client_ip(),
				),
			);
			D('user')->relation(true)->where(array('id'=>$user['id']))->save($arr);
			//保存session
			session('uid',$user['id']);
	    	session('username',$user['username']);
	    	//成功提示信息
    		$data['error']='';
	    	$data['tip']='登录成功！';
	    	$data['rememberme']=$rememberme;
	    	$data['user']=$value;
	    	$data['avatar']='http://www.sucaihuo.com/Public/images/avatar.jpg';
	    	echo json_encode($data);
		}
	}

	//修改个人介绍
	public function intro(){
		if(!IS_AJAX || !$_SESSION['username']){$this->error('非法操作！',U('Account/login'));}
		D('userinfo')->where(array('uid'=>session('uid')))->save(array('intro'=>I('content')));
	}

	public function ceshi(){
		sendMail('710298639@qq.com','账号激活','点击激活账号');
	}

	public function topic_post(){
		if(!IS_AJAX || !$_SESSION['username']){$this->error('非法操作！',U('Account/login'));}
		if(IS_POST){
			if($this->check_verify(I('code'))){
				$data['cateid']=I('cat_id');
				$data['content']=I('content');
				$data['attachment']=I('file_path');
                $keywords=I('tags');
				$data['keywords']=str_replace('×','',$keywords);
				$data['title']=I('title');
				$data['uid']=session('uid');
				$data['time']=time();
				if(D('topic')->add($data)){
					$dat['error']='';
					echo json_encode($dat);
				}else{
					$dat['error']='发布失败！';
					echo json_encode($dat);
				}
			}else{
				$dat['error']='验证码错误！';
				echo json_encode($dat);
			}
		}else{
			$dat['error']='非法操作！';
			echo json_encode($dat);
		}
	}
	//验证发布话题处验证码
	function check_verify($code, $id = ''){
		$verify = new \Think\Verify();
		return $verify->check($code, $id);
	}
	//上传附件
    public function upfile(){
        $upload=$this->_upfile('Attachment');
        echo json_encode($upload);
       
    }

    public function setface(){
        $userinfo=D('userinfo');
        $where=array('uid'=>session('uid'));
        $field=array('face50','face80','face180','points');
        $old=$userinfo->where($where)->field($field)->find();
        $arr=array(
            'face50'=>I('small'),
            'face80'=>I('mid'),
            'face180'=>I('max'),
            );
        if($userinfo->where($where)->save($arr)){
            if(!empty($old['face180'])){
                unlink($old['face180']);
                unlink($old['face80']);
                unlink($old['face50']);
            }else{
                $arr=array(
                    'points'=>$old['points']+C('FACE'),
                    );
                $userinfo->where($where)->save($arr);
            }

            echo 1;
        }else{
            echo 0;
        }
    }

    //附件处理
    private function _upfile($path){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 8145728;
        $upload->rootPath = './';
        $upload->savePath = './Public/Uploads/'.$path.'/';
        $upload->saveName = array('uniqid','');
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg','doc','rar');
        $upload->autoSub  = true;
        $upload->subName  = array('date','Ym');
        if($info=$upload->upload()){
            $filepath=$upload->savePath.date('Ym').'/'.$info['Filedata']['savename'];
            return array(
                'status'=>1,
                'filename'=>$info['Filedata']['savename'],
                'filepath'=>$filepath,
                );
        }else{
            return array('status'=>0,'msg'=>$upload->getError());
        }
    }

    //收藏功能
    public function getCollect(){
    	$keep=D('keep');
    	$data['type']=I('mtype');
    	$data['arid']=I('id');
    	$data['uid']=session('uid');
    	if($keep->where($data)->find()){
    		$keep->where($data)->delete();
    		echo '';
    	}else{
    		$data['time']=time();
    		$id=$keep->add($data);
    		echo $id;
    	}
    }

    

   

    //查找touid

    public function touid($pidsub){
        $commss=D('comment')->where(array('id'=>$pidsub))->find();
        if($commss['pidsub']==0){
            return $commss['id'];
        }

        while ($commss['pidsub']) {
           $commss=D('comment')->where(array('id'=>$commss['pidsub']))->find();
           $pidsub=$commss['id'];
        }

        return $pidsub;


    }


    //异步评论功能
    public function subcomment(){
    	if(!IS_AJAX || !$_SESSION['username']){$this->error('非法操作！',U('Account/login'));}
    	$comm=D('comment');
    	$data['uid']=session('uid');
    	$data['artid']=I('id');
    	$data['type']=I('mtype');
    	$data['content']=I('content');
    	$data['time']=time();
    	$data['pid']=I('pid');
        if(I('pid_sub')){
            $data['pidsub']=I('pid_sub');
            $comms=D('comment')->where(array('id'=>$data['pidsub']))->find();
            $data['tid']=$comms['uid'];
            $users=D('userinfo')->where(array('uid'=>$data['tid']))->find();
            $data['tuser']=$users['nickname'];
            $data['touid']=$this->touid($data['pidsub']);
        }
    	$old=$comm->order('id desc')->find();
    	$old=$old['time'];
    	$tim=time()-$old;
    	if($tim<10){
    		$dat['code']='fast';
    		$dat['error']='您提交评论的速度太快了，请稍后再发表评论。';
    		echo json_encode($dat); 
    		die;
    	}
    	$content=strlen($data['content']);
    	if($content<10){
    		$dat['code']='short than 10';
    		$dat['error']='评论的内容不能少于10个字符。';
    		echo json_encode($dat); 
    		die;
    	}
    	if($comm->add($data)){
            D('topic')->where(array('id'=>$data['artid']))->setInc('comment');
    		$dat['code']=200;
    		$dat['points']=0;
    		$dat['comment']=$data['content'];
    		echo json_encode($dat);
    	}else{
    		echo '';
    	}

    }





	


	
}